<?php

namespace app\admin\model;

use think\Model;

class AuthRule extends Model {

    function authRuleTree()
    {
        $data = $this->order('id desc')->select();
        return $this->sort($data);
    }

    function sort($data, $pid = 0)
    {

        static $sortArr = array();
        foreach ($data as $key => $value) {

            if ($pid == $value['pid']) {

                $value['dataid'] = $this->recursiveGetParentId($value['id'], true);
                $sortArr[] = $value;

                // 递归
                $this->sort($data, $value['id']);
            }

        }

        return $sortArr;
    }

    /**
     * 递归获取子权限的所有id
     */
    function recursiveGetId($pid)
    {

        static $arr = array();

        // 查询指定pid的下一级权限
        $sonAuth = self::all(['pid' => $pid]);

        if (!empty($sonAuth)) { // 有下一级权限
            foreach ($sonAuth as $k => $v) {
                $arr[] = $v['id'];
                $this->recursiveGetId($v['id']);
            }
        }

        return $arr;

    }

    /**
     * 递归获取所有父权限的id
     */
    function recursiveGetParentId($id, $clear = false)
    {
        static $arr = array();

        if ($clear) {// 每递归一次顶级权限清空一次数组
            $arr = array();
        }

        // 查询指定id的权限
        $parentAuth = self::all(['id' => $id]);

        if (!empty($parentAuth)) {// 有上一级权限
            foreach ($parentAuth as $k => $v) {
                $arr[] = $v['id'];
                $this->recursiveGetParentId($v['pid']);
            }
        }

        asort($arr);
        $sortStr = implode('-', $arr);
        return $sortStr;
    }

    /**
     * 递归删除子权限
     */
    function recursiveDelSonRules($id)
    {
        // 获取当前权限下所有子权限的id
        $sonIDs = $this->recursiveGetId($id);

        // 删除所有的子权限
        if (!empty($sonIDs)) {
            self::destroy($sonIDs);
        }
    }

}
